package edu.odu.cs.sstore.repository;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import edu.odu.cs.sstore.domain.Course;
import edu.odu.cs.sstore.domain.User;

@Repository
public class CourseRepositoryImpl implements CourseRepository {
	
	@Autowired(required=true)
	private SessionFactory sessionFactory;
 
	public Course saveOrUpdate(Course course) {
		this.sessionFactory.getCurrentSession().saveOrUpdate(course);
		return course;
	}
	
	public Course findByCRN(Long crn) {
		return (Course) this.sessionFactory.getCurrentSession().createQuery(
			"from Course course where course.crn=?").setParameter(0, crn)
			.uniqueResult();
	}

	@SuppressWarnings("unchecked")
	public List<Course> findByFaculty(User faculty) {
		return (List<Course>)sessionFactory.getCurrentSession().createQuery(
			"from Course course where course.faculty=? order by course.code")
			.setParameter(0,faculty).list();
	}

	public void deleteCourse(Course course) {
		this.sessionFactory.getCurrentSession().delete(course);
	}

}
